package com.suoyue.store.controller;

import com.suoyue.store.entity.User;
import com.suoyue.store.service.IUserservice;
import com.suoyue.store.service.ex.ServiceException;
import com.suoyue.store.service.ex.UsernameDuplicatedException;
import com.suoyue.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("users")
public class UserController extends BaseController{
    @Autowired
    IUserservice iUserservice;

    @RequestMapping("reg")
    public JsonResult<Void> reg(User user) {
        // 调用业务对象执行注册
        iUserservice.regist(user);
        // 返回
        return new JsonResult<Void>(OK);
    }

    @RequestMapping("login")
    public JsonResult<User> login(String name, String password, HttpSession session) {
        // 调用业务对象的方法执行登录，并获取返回值
        User data = iUserservice.login(name, password);
        session.setAttribute("uid", data.getUid());
        session.setAttribute("username", data.getUsername());
        System.out.println(getUidFromSession(session));
        // 将以上返回值和状态码OK封装到响应结果中并返回
        return new JsonResult<User>(OK, data);
    }

    @RequestMapping("getsession")
    public JsonResult<User> getsession(HttpSession session) {

        User data=new User();
        data.setUsername(getUsernameFromSession(session));
        data.setUid(getUidFromSession(session));

        // 将以上返回值和状态码OK封装到响应结果中并返回
        return new JsonResult<User>(OK, data);
    }

//注销
    @RequestMapping("logout")
    public JsonResult<String> test(HttpSession session) {


        // 调用业务对象的方法执行登录，并获取返回值

        session.removeAttribute("uid");
        session.removeAttribute("username");


//        session.setAttribute("uid", data.getUid());
//        session.setAttribute("username", data.getName());
//        System.out.println(getUidFromSession(session));

        // 将以上返回值和状态码OK封装到响应结果中并返回
        // 将以上返回值和状态码OK封装到响应结果中并返回
        return new JsonResult<String>(OK);
    }
}
